import React from 'react';
import { toJS } from 'mobx';
import * as _ from 'lodash';
import { Radio, Spin, Button } from 'antd';
import { WeaRangePicker, WeaLocaleProvider, WeaDialog, WeaTable, WeaAlertPage, WeaNewScroll } from 'ecCom';
import ChartPanel from '../../../public/chartpanel/ChartPanel';
import * as Util from "../../../util/Util"
import * as teamPortraitApis from '../../../apis/portrait/teamPortrait';

const getLabel = WeaLocaleProvider.getLabel;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

export default class TeamPortraitIndex extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            ...props,
            isloading: false, // 整个页面是否还有数据在加载
            efficiencyAnalysisLoading: false, // 工作效率分析是否还有数据在加载
            leaveDaysLoading: false, // 请假天数数据是否正在加载
            comeLateTimesLoading: false, // 迟到次数数据是否正在加载
            leaveEarlyTimesLoading: false, // 早退次数数据是否正在加载
            absentTimesLoading: false, // 旷工次数数据是否正在加载
            interfacesInfo: {},
            radioSelectedKey: '1',
            dateRangeValue: ["", ""],
            efficiencyAnalysisDatas: [],
            attendenceStatDatas: {
                slogan: {
                    avgAttendence: {
                        label: '0%',
                        color: '#1589DD',
                    },
                    passrate: {
                        label: '0%',
                        color: '#DB8A2B',
                    },
                },
                leaveDays: [],
                comeLateTimes: [],
                leaveEarlyTimes: [],
                absentTimes: [],
            },
        };
    }

    componentWillMount() {
        // 模拟请求接口数据
        this.getPageDatas();
    }

    componentWillReceiveProps(newProps) {
        if (!_.isEqual(this.props, newProps)) {
            this.setState({
                ...this.state,
                ...newProps,
            }, () => {
                this.getPageDatas();
            });
        }
    }

    // 根据风险项获取风险数据
    getRiskItemData = risk => {
        return new Promise((rs) => {
            const handleRes = (res) => {
                const { data } = res
                if (data) {
                    if (_.isEmpty(data._flagField)) {
                        data._flagField = "compare"
                    }
                    // console.log(data)
                    let sloganDatas = {}
                    Object.keys(data).forEach((key) => {
                        if (!["_flagField", "_flagType"].includes(key)) {
                            let label = data[key]
                            if (key == "compare") {
                                label = data[key] == "1" ? getLabel('522391', '低于') : (data[key] == "0" ? "" : getLabel('522473', '高于'))
                            }
                            sloganDatas[key] = {
                                label,
                                color: key == data._flagField ? (data._flagType == "1" ? "#60C498" : "#F56C6C") : "#DB8A2B",
                            }
                        }
                    })
                    this.state.efficiencyAnalysisDatas.push({
                        showorder: parseInt(risk.showorder + ""),
                        slogan: [
                            risk.tipsinfo,
                            sloganDatas,
                        ],
                        icon: {
                            type: data._flagType == "1" ? 'icon-coms02-icon-Completion' : "icon-coms02-Warning-01",
                            color: data._flagType == "1" ? '#74AB00' : '#E6A23C',
                        },
                    })
                    this.setState({
                        efficiencyAnalysisDatas: this.state.efficiencyAnalysisDatas.sort((a, b) => a.showorder - b.showorder),
                    })
                }
                rs()
            }

            if (risk.interfaceinfo) {
                teamPortraitApis.getRiskDataByInterfaceinfo({
                    interfaceinfo: risk.interfaceinfo,
                    ...this.getBaseRequestParams()
                }).then((res) => {
                    handleRes(res)
                })
            } else {               // to delete
                let res = {}
                if (risk.showorder == 0) {
                    res.data = {
                        count1: 61,
                        amount: '8%',
                        compare: "1", //   1--低于  2--高于    getLabel('522391', '低于'),   // getLabel('522473', '高于')
                        amount_ave: '21%',
                        _flagType: "1"    // 1代表成功  2代表警告
                    }
                } else if (risk.showorder == 1) {
                    res.data = {
                        amount: '1天23小时',
                        compare: "1",
                        amount_ave: '5天2小时',
                        _flagType: "1"
                    }
                } else if (risk.showorder == 2) {
                    res.data = {
                        amount: '95.6%',
                        compare: "1",
                        amount_ave: '99.6%',
                        _flagType: "2"
                    }
                } else if (risk.showorder == 3) {
                    res.data = {
                        amount: '15.59',
                        compare: "2",
                        amount_ave: '7.68',
                        _flagType: "2"
                    }
                } else if (risk.showorder == 4) {
                    res.data = {
                        amount: '8',
                        compare: "2",
                        amount_ave: '7.88',
                        _flagType: "1"
                    }
                } else if (risk.showorder == 5) {
                    res.data = {
                        amount: '88%',
                        compare: "2",
                        amount_ave: '85%',
                        _flagType: "1"
                    }
                }
                handleRes(res)
            }
        })
    }

    // 加载工作效率分析数据
    loadEfficiencyAnalysisDatas = () => {
        return new Promise((rs) => {
            this.setState({
                efficiencyAnalysisLoading: true,
                efficiencyAnalysisDatas: [],
            })
            const { subId, deptId, includeSub } = this.state
            teamPortraitApis.getTeamRisk({ subDeptId: subId || deptId, type: subId ? "1" : "2", includeSub: includeSub ? "1" : "0" }).then((res) => {
                if (res.status == '1') {
                    if (res.data && res.data.length > 0) {
                        Promise.all(res.data.map(d => this.getRiskItemData(d))).then((v) => {
                            this.setState({
                                efficiencyAnalysisLoading: false,
                            })
                            rs()
                        })
                    } else {
                        this.setState({
                            efficiencyAnalysisLoading: false,
                        })
                        rs()
                    }
                }
            })
        })
    }

    // 获取出勤统计总结性描述信息
    getAttendenceStatDesc = () => {
        return new Promise(rs => {
            const handleRes = (res) => {
                let { data } = res
                if (data) {
                    let slogan = {}
                    slogan.avgAttendence = {
                        label: data.avgAttendence,
                        color: '#1589DD',
                    };
                    slogan.passrate = {
                        label: data.passrate,
                        color: '#DB8A2B',
                    }
                    this.state.attendenceStatDatas.slogan = slogan
                    this.setState({
                        attendenceStatDatas: { ...this.state.attendenceStatDatas },
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1007").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: {
                        avgAttendence: '88%', // 平均出勤率
                        passrate: '56.7%', // 超过比例
                    }
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 获取请假天数数据
    getLeaveDaysData = () => {
        return new Promise((rs) => {
            this.setState({
                leaveDaysLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    leaveDaysLoading: false
                })
                let { data } = res
                if (data) {
                    let formatedDatas = []
                    data.forEach((r) => {
                        formatedDatas.push({
                            yd: r.item,
                            xd: r.count,
                            color: ['rgba(45,183,245,0.4)', 'rgba(45,183,245,1)'],
                        })
                    })
                    this.state.attendenceStatDatas.leaveDays = formatedDatas
                    this.setState({
                        attendenceStatDatas: { ...this.state.attendenceStatDatas }
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1008").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: [
                        {
                            item: '杨文元', // 请假人
                            count: 18.5, // 请假天数
                        },
                        {
                            item: '李妍',
                            count: 20,
                        },
                    ]
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 获取迟到次数数据
    getComeLateTimesDatas = () => {
        return new Promise((rs) => {
            this.setState({
                comeLateTimesLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    comeLateTimesLoading: false
                })
                let { data } = res
                if (data) {
                    let formatedDatas = []
                    data.forEach((r) => {
                        formatedDatas.push({
                            yd: r.item,
                            xd: r.count,
                            color: ['rgba(241,171,61,0.4)', 'rgba(241,171,61,1)'],
                        })
                    })
                    this.state.attendenceStatDatas.comeLateTimes = formatedDatas
                    this.setState({
                        attendenceStatDatas: { ...this.state.attendenceStatDatas },
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1009").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: [
                        {
                            item: '刘长庚', // 迟到人
                            count: 14, // 迟到次数
                        },
                        {
                            item: '傅雷',
                            count: 8,
                        },
                    ]
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 获取早退次数数据
    getLeaveEarlyTimesDatas = () => new Promise((rs) => {
        this.setState({
            leaveEarlyTimesLoading: true,
        });

        const handleRes = (res) => {
            this.setState({
                leaveEarlyTimesLoading: false
            })
            let { data } = res
            if (data) {
                let formatedDatas = []
                data.forEach((r) => {
                    formatedDatas.push({
                        yd: r.item,
                        xd: r.count,
                        color: ['rgba(251,138,138,0.4)', 'rgba(251,138,138,1)'],
                    })
                })
                this.state.attendenceStatDatas.leaveEarlyTimes = formatedDatas
                this.setState({
                    attendenceStatDatas: { ...this.state.attendenceStatDatas },
                })
            }
            rs()
        }

        // this.getDataByInterfaceCode("1010").then(res => {
        //     handleRes(res)
        // })

        window.setTimeout(() => {
            let res = {
                data: [
                    {
                        item: '王芳', // 早退人
                        count: 28, // 早退次数
                    },
                    {
                        item: '周刚',
                        count: 17,
                    },
                ]
            }
            handleRes(res)
        }, 1000);
    })

    // 获取旷工次数数据
    getAbsentTimesDatas = () => new Promise((rs) => {
        this.setState({
            absentTimesLoading: true,
        });

        const handleRes = (res) => {
            this.setState({
                absentTimesLoading: false
            })
            let { data } = res
            if (data) {
                let formatedDatas = []
                data.forEach((r) => {
                    formatedDatas.push({
                        yd: r.item,
                        xd: r.count,
                        color: ['rgba(238,0,0,0.4)', 'rgba(238,0,0,1)'],
                    })
                })
                this.state.attendenceStatDatas.absentTimes = formatedDatas
                this.setState({
                    attendenceStatDatas: { ...this.state.attendenceStatDatas },
                })
            }
            rs()
        }

        // this.getDataByInterfaceCode("1011").then(res => {
        //     handleRes(res)
        // })

        window.setTimeout(() => {
            let res = {
                data: [
                    {
                        item: '张静', // 旷工人
                        count: 7, // 旷工次数
                    },
                    {
                        item: '徐萍',
                        count: 5,
                    },
                ]
            }
            handleRes(res)
        }, 1000);
    })

    // 加载出勤统计数据
    loadAttendenceStatDatas = () => {
        return Promise.all([this.getAttendenceStatDesc(), this.getLeaveDaysData(), this.getComeLateTimesDatas(), this.getLeaveEarlyTimesDatas(), this.getAbsentTimesDatas()])
    }

    // 获取页面展示所需数据
    getPageDatas = () => {
        const { subId, deptId, includeSub, interfacesInfo } = this.state
        if (!_.isEmpty(subId) || !_.isEmpty(deptId)) {
            new Promise(rs => {
                if (_.isEmpty(interfacesInfo)) {
                    teamPortraitApis.getInterfacesInfo({
                        codes: "1007,1008,1009,1010,1011"
                    }).then(res => {
                        this.setState({
                            interfacesInfo: res.data || {}
                        }, () => rs())
                    })
                } else {
                    rs()
                }
            }).then(v => {
                Promise.all([
                    this.loadEfficiencyAnalysisDatas(),
                    this.loadAttendenceStatDatas()
                ])
            })
        }
    }

    // 根据接口code获取数据
    getDataByInterfaceCode = (code) => {
        const { interfacesInfo } = this.state
        const interfaceObj = interfacesInfo[code]
        if (interfaceObj && interfaceObj.addr) {
            return WeaTools.callApi(interfaceObj.addr, interfaceObj.method || "GET", {
                ...this.getBaseRequestParams(),
                pagenum: 1,
                pagesize: 5
            })
        } else {
            return new Promise(rs => rs({}))
        }
    }

    getSloganHtml = (slogan) => {
        if (_.isString(slogan)) {
            return `${slogan}`;
        } else if (_.isArray(slogan)) {
            let result = slogan[0];
            Object.keys(slogan[1] || {}).forEach((key) => {
                let reg;
                if (result.indexOf('$') > -1) {
                    reg = `\${${key}}`;
                } else {
                    reg = `&${key}&`;
                }
                result = result.replace(reg, `<span style="font-size: 18px; padding: 0 5px; color: ${slogan[1][key].color || '#333'}">${slogan[1][key].label}</span>`);
            });
            return result;
        }
    }

    onDatePickerChange = (value) => {
        this.setState({
            dateRangeValue: value,
        }, () => {
            if (value && value[0] && value[1]) {
                this.getPageDatas();
            }
        });
    }

    onRadioChange = (e) => {
        const newkey = e.target.value;
        this.setState({
            radioSelectedKey: newkey,
        }, () => {
            if (newkey != '7') {
                this.getPageDatas();
            } else {
                if (this.state.dateRangeValue && this.state.dateRangeValue[0] && this.state.dateRangeValue[1]) {
                    this.getPageDatas();
                }
            }
        });
    }

    getBaseRequestParams = () => {
        const { subId, deptId, includeSub, radioSelectedKey, dateRangeValue } = this.state
        return {
            subId,
            deptId,
            includeSub: includeSub ? "1" : "0",
            datetype: radioSelectedKey == "7" ? dateRangeValue.join(",") : radioSelectedKey
        }
    }

    render() {
        const { isloading, efficiencyAnalysisLoading, leaveDaysLoading, comeLateTimesLoading, leaveEarlyTimesLoading, absentTimesLoading,
            radioSelectedKey, dateRangeValue, efficiencyAnalysisDatas, attendenceStatDatas, interfacesInfo,
            moreDialogVisible, moreDialogTitle, moreDialogTableColumns, moreDialogTableDataSource } = this.state

        const baseRequestParams = this.getBaseRequestParams()

        return (
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@op0sia`} spinning={isloading}>
                <div className="wea-workrelate-team-portrait-riskmanage">
                    <div className="radio-select-wrapper">
                        <div className="radio-group-wrapper">
                            <RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@7hmfnq`}
                                onChange={this.onRadioChange}
                                value={radioSelectedKey}
                            >
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@w622zk`} value={'1'}>{getLabel('84002', '上一月')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@fjptb1`} value={'2'}>{getLabel('15541', '本月')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@6rcz8u`} value={'3'}>{getLabel('21904', '本季')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@qaiw1i`} value={'4'}>{getLabel('383369', '上一季')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@5uw3zn`} value={'5'}>{getLabel('15384', '本年')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@18yumb`} value={'6'}>{getLabel('81716', '上一年')}</RadioButton>
                                <RadioButton ecId={`${this && this.props && this.props.ecId || ''}_RadioButton@t7xcn5`} value={'7'}>{getLabel('32530', '指定日期范围')}</RadioButton>
                            </RadioGroup>
                        </div>
                        {
                            radioSelectedKey == '7' &&
                            <div className="date-picker-wrapper">
                                <WeaRangePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaRangePicker@phry4r`}
                                    value={dateRangeValue}
                                    onChange={this.onDatePickerChange}
                                />
                            </div>
                        }
                        <span className="stat-endinfo">
                            {`${getLabel('523864','数据统计截止到')} ${Util.getLastDateStr()} 23:59:59`}
                        </span>
                    </div>

                    <div className="efficiency-analysis-wrapper">
                        <div className="title-wrapper">
                            {getLabel('522396', '工作效率分析')}
                        </div>
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@05yqik`} spinning={efficiencyAnalysisLoading}>
                            <div className="list-content-wrapper">
                                {/* <div className="left-icon">
                                    <i className="icon-portal-kpi" />
                                </div> */}
                                {
                                    efficiencyAnalysisDatas.length == 0 ?
                                        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@zomati`} icon={<i className="icon-coms-NoData" />} iconSize={25} >
                                            <div style={{ textAlign: "center", marginTop: "4px" }}>
                                                {getLabel(83553, "暂无数据")}
                                            </div>
                                        </WeaAlertPage>
                                        :
                                        <div className="right-data">
                                            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@04xzma`}
                                                height={198}
                                            >
                                                <div className="right-data-abs">
                                                    {
                                                        efficiencyAnalysisDatas.map(d => (
                                                            <div className="data-item">
                                                                <span className="icon">
                                                                    {
                                                                        d.icon && <i className={d.icon.type} style={{ color: d.icon.color }} />
                                                                    }
                                                                </span>
                                                                <span className="text" dangerouslySetInnerHTML={{ __html: this.getSloganHtml(d.slogan) }} />
                                                            </div>
                                                        ))
                                                    }
                                                </div>
                                            </WeaNewScroll>
                                        </div>
                                }
                            </div>
                        </Spin>
                    </div>

                    <ChartPanel ecId={`${this && this.props && this.props.ecId || ''}_ChartPanel@gu33md`}
                        ismock={true}            //  to delete
                        style={{ marginTop: '20px' }}
                        title={getLabel('16732', '出勤统计')}
                        slogan={[
                            getLabel('522445', '平均出勤率${avgAttendence}，超过${passrate}的其他部门'),
                            attendenceStatDatas.slogan,
                        ]}
                        charts={[
                            {
                                type: 'strip',
                                width: '45%',
                                height: 300,
                                title: getLabel('522398', '请假天数统计'),
                                data: attendenceStatDatas.leaveDays,
                                loading: leaveDaysLoading,
                                scale: {
                                    yd: {
                                        formatter: val => getLabel('828', '请假天数'),
                                    },
                                },
                                noborder: true,
                                nobottom: true,
                                hasmore: true,
                                moreProps: {
                                    table: {
                                        columns: [
                                            {
                                                title: getLabel(25034, '姓名'),
                                                dataIndex: 'item',
                                                key: 'item'
                                            },
                                            {
                                                title: getLabel('828', '请假天数'),
                                                dataIndex: 'count',
                                                key: 'count'
                                            }
                                        ],
                                        interface: interfacesInfo["1008"] || {},
                                        baseRequestParams
                                    }
                                }
                            },
                            {
                                type: 'strip',
                                width: '45%',
                                height: 300,
                                title: getLabel('522399', '迟到次数统计'),
                                data: attendenceStatDatas.comeLateTimes,
                                loading: comeLateTimesLoading,
                                scale: {
                                    yd: {
                                        formatter: val => getLabel('33899', '迟到次数'),
                                    },
                                },
                                noborder: true,
                                nobottom: true,
                                hasmore: true,
                                moreProps: {
                                    table: {
                                        columns: [
                                            {
                                                title: getLabel(25034, '姓名'),
                                                dataIndex: 'item',
                                                key: 'item'
                                            },
                                            {
                                                title: getLabel('33899', '迟到次数'),
                                                dataIndex: 'count',
                                                key: 'count'
                                            }
                                        ],
                                        interface: interfacesInfo["1009"] || {},
                                        baseRequestParams
                                    }
                                }
                            },
                            {
                                type: 'strip',
                                width: '45%',
                                height: 300,
                                style: { marginTop: '30px' },
                                title: getLabel('522400', '早退次数统计'),
                                data: attendenceStatDatas.leaveEarlyTimes,
                                loading: leaveEarlyTimesLoading,
                                scale: {
                                    yd: {
                                        formatter: val => getLabel('522401', '早退次数'),
                                    },
                                },
                                noborder: true,
                                nobottom: true,
                                hasmore: true,
                                moreProps: {
                                    table: {
                                        columns: [
                                            {
                                                title: getLabel(25034, '姓名'),
                                                dataIndex: 'item',
                                                key: 'item'
                                            },
                                            {
                                                title: getLabel('522401', '早退次数'),
                                                dataIndex: 'count',
                                                key: 'count'
                                            }
                                        ],
                                        interface: interfacesInfo["1010"] || {},
                                        baseRequestParams
                                    }
                                }
                            },
                            {
                                type: 'strip',
                                width: '45%',
                                height: 300,
                                style: { marginTop: '30px' },
                                title: getLabel('522402', '旷工次数统计'),
                                data: attendenceStatDatas.absentTimes,
                                loading: absentTimesLoading,
                                scale: {
                                    yd: {
                                        formatter: val => getLabel('522403', '旷工次数'),
                                    },
                                },
                                noborder: true,
                                nobottom: true,
                                hasmore: true,
                                moreProps: {
                                    table: {
                                        columns: [
                                            {
                                                title: getLabel(25034, '姓名'),
                                                dataIndex: 'item',
                                                key: 'item'
                                            },
                                            {
                                                title: getLabel('522403', '旷工次数'),
                                                dataIndex: 'count',
                                                key: 'count'
                                            }
                                        ],
                                        interface: interfacesInfo["1011"] || {},
                                        baseRequestParams
                                    }
                                }
                            }
                        ]}
                    />
                </div>
            </Spin>
        );
    }
}
